Overview
TheClipLoss class implements the symmetric cross-entropy loss used to train CLIP models. It computes contrastive loss between image and text features by treating each image-text pair as a positive match and all other pairs in the batch as negatives.
The loss is computed as the average of:
- Image-to-text classification loss
- Text-to-image classification loss
- Distributed training support - Efficient all-gather operations across GPUs
- Local loss option - Compute loss only on local batch for memory efficiency
- Label caching - Cache ground truth labels for faster training
- Horovod support - Alternative distributed backend
Class Definition
Initialization Parameters
bool
default:"False"
If True, computes loss only between local image features and gathered text features (and vice versa). Reduces memory usage in distributed training but changes the gradient dynamics.
bool
default:"False"
If True, gathers features with gradient flow enabled. Required for certain distributed training strategies but increases memory usage.
bool
default:"False"
If True, caches ground truth labels to avoid recomputing them each forward pass. Saves computation at the cost of memory.
int
default:"0"
Current process rank in distributed training. Should match the rank from your distributed backend.
int
default:"1"
Total number of processes in distributed training. Set to 1 for single-GPU training.
bool
default:"False"
If True, uses Horovod for distributed operations instead of torch.distributed.
Attributes
- local_loss: Whether local loss mode is enabled
- gather_with_grad: Whether gradient flows through gather operations
- cache_labels: Whether label caching is enabled
- rank: Current process rank
- world_size: Total number of processes
- use_horovod: Whether using Horovod backend
- prev_num_logits: Cached logits count for label caching
- labels: Dictionary of cached label tensors per device
Key Methods
forward
image_features: Normalized image features of shape(batch_size, embed_dim)text_features: Normalized text features of shape(batch_size, embed_dim)logit_scale: Temperature parameter (typicallymodel.logit_scale.exp())logit_bias: Optional bias term to add to logitsoutput_dict: If True, returns dict with key “contrastive_loss”, else returns scalar
get_logits
get_ground_truth
(num_logits,) with values [0, 1, 2, …, num_logits-1]
Usage Example
Distributed Training Example
Local Loss Example
With Logit Bias
Dictionary Output
Performance Considerations
Memory vs. Accuracy Trade-offs:
Best Practices:
- Enable
cache_labels=Truefor training (slight memory cost, faster) - Use
local_loss=Trueonly when memory is constrained - Set
gather_with_grad=Falsefor most use cases - Ensure features are normalized before passing to loss
Mathematical Formulation
Given normalized image features and text features :-
Compute logits:
- =
logit_scale.exp() - =
logit_bias(optional)
- =
- Compute symmetric cross-entropy: where labels = (diagonal is positive)
- In distributed setting, features are gathered from all GPUs before computing logits
Related
- CLIP - Model that uses this loss
- CoCaLoss - Extended loss with caption generation
- SigLipLoss - Alternative sigmoid-based loss
